jQ(function(){
	jQ("#countdown").data("num",5);
	analyzeUrl();
});

function analyzeUrl(){
	var param=getUniqueParameter();
	if(param==null||param.length==0){
		jQ("#requestresult").empty().append("访问错误");
		jQ("#countdown").next().empty().append("秒后跳转至订阅主页");
		startCooldown(jQ("#ctxVal").val()+"/clipsubscribe.html");
	}else{
		if(param.indexOf("IN")==0||param.indexOf("OUT")==0){
			if(param.indexOf("_")<=0){
				jQ("#requestresult").empty().append("访问错误");
				jQ("#countdown").next().empty().append("秒后跳转至订阅主页");
				startCooldown(jQ("#ctxVal").val()+"/clipsubscribe.html");
			}else{
				var arr=param.split("_");
				if(arr[0]=="IN"){
					confirmsubscribe(arr[1]);
				}else if(arr[0]=="OUT"){
					unsubscribe(arr[1]);
				}
			}
		}else{
			jQ("#requestresult").empty().append("访问错误");
			jQ("#countdown").next().empty().append("秒后跳转至订阅主页");
			startCooldown(jQ("#ctxVal").val()+"/clipsubscribe.html");
		}
	}
}

function getUniqueParameter(){
    var paramStr=location.search;
    if(paramStr.length==0)return null;
    if(paramStr.charAt(0)!='?')return null;
    paramStr=unescape(paramStr);
    paramStr=paramStr.substring(1);
    if(paramStr.length==0)return null;
    return paramStr;
}

function startCooldown(url){
	var forwardurl=url;
	var scroll=setInterval(function(){
		var num=eval(jQ("#countdown").data("num"));
		num--;
		if(num<1){
			clearInterval(scroll);
			window.location.href=forwardurl;
		}else{
			jQ("#countdown").data("num",num);
			jQ("#countdown").text(num);
		}
	},1000);
}

function confirmsubscribe(uuid){
	jQ.ajax({
		type: "POST",
		url:"contactAjax!confirmSubscribeForEmail.action",
		data:{
			optcode:uuid
		},
		success:function(data){
			var url;
			if(data.result){
				jQ("#requestresult").empty().append("恭喜你订阅<font>"+data.name+"</font>成功！");
				jQ("#countdown").next().empty().append("秒后跳转至 "+data.name+" 主页");
				url=jQ("#ctxVal").val()+"/myclip/user.html?"+data.uid;
			}else{
				jQ("#requestresult").empty().append("访问错误");
				jQ("#countdown").next().empty().append("秒后跳转至订阅主页");
				url=jQ("#ctxVal").val()+"/clipsubscribe.html";
			}
			startCooldown(url);
		}
	});
}

function unsubscribe(uuid){
	jQ.ajax({
		type: "POST",
		url:"contactAjax!unsubscribeForEmail.action",
		data:{
			optcode:uuid
		},
		success:function(data){
			if(data.result){
				jQ("#requestresult").empty().append("你已取消对<font>"+data.name+"</font>的订阅");
				jQ("#countdown").next().empty().append("秒后跳转至订阅主页");
			}else{
				jQ("#requestresult").empty().append("访问错误");
				jQ("#countdown").next().empty().append("秒后跳转至订阅主页");
			}
			startCooldown(jQ("#ctxVal").val()+"/clipsubscribe.html");
		}
	});
}